package com.cnswhy.cloud.common.core.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ClaseName：BaseUtils
 * Description：日常业务工具类
 * Author：JensenWei
 * QQ: 2188307188
 * Createtime：2018/11/6 10:16
 * Modified By：
 * Fixtime：2018/11/6 10:16
 * FixDescription：
 */
public class BaseUtils {


    /*
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 检查是否存在汉字
     *
     * @param countname
     * @return 存在为true
     */
    public static boolean checkChinese(String countname) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(countname);
        if (m.find()) {
            return true;
        }
        return false;
    }


    /**
     * 排序并组装签名明文串
     *
     * @param map
     * @return
     */
    public static String hex(Map<String, String> map) {
        String[] strs = new String[map.size()];
        map.keySet().toArray(strs);
        Arrays.sort(strs);
        StringBuffer source = new StringBuffer();
        for (String str : strs) {
            if (!StringUtils.isEmpty(map.get(str))) {//空值不添加进去
                source.append(str + "=" + map.get(str) + "&");
            }
        }
        String bigstr = source.substring(0, source.length() - 1);
        return bigstr;
    }

    /**
     * 格式化BigDecimal，以免丢失精度
     *
     * @param s
     * @return
     */
    public static BigDecimal formatBigDecimal(Object s) {
        return new BigDecimal(s.toString());
    }


    /**
     * 以当前时间数+四位随机数作为订单号
     *
     * @return
     */
    public static String createOrderId() {
        String temp;
        String time = Kits.Date.getyyyyMMddHHmmss();
        temp = "O" + time + Kits.Random.getRandomNumbersAndLetters(4);
        return temp;
    }

    /**
     * 根据请求获取ip
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，那么取第一个ip为客户端ip
        if (ip != null && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }
        return ip;
    }

    /**
     * 分割list大小
     *
     * @param targetList
     * @param splitSize
     * @param <E>
     * @return
     */
    public static <E> List<List<E>> splitList(List<E> targetList, Integer splitSize) {
        if (targetList == null) return null;
        Integer size = targetList.size();
        List<List<E>> resultList = new ArrayList<List<E>>();
        if (size <= splitSize) {
            resultList.add(targetList);
        } else {
            for (int i = 0; i < size; i += splitSize) {
                //用于限制最后一部分size小于splitSize的list
                Integer limit = i + splitSize;
                if (limit > size) {
                    limit = size;
                }
                resultList.add(targetList.subList(i, limit));
            }
        }
        return resultList;
    }

    /**
     * 格式化卡号（卡号脱敏）
     *
     * @param card
     * @return
     */
    public static String formatCard(String card) {
        if (StringUtils.isEmpty(card) || card.length() <= 8) {
            return card;
        }
        return replaceString(card, "****", 4, card.length() - 4);
    }

    public static String formatPhone(String phone) {
        if (StringUtils.isEmpty(phone) || phone.length() != 11) {
            return phone;
        }
        return replaceString(phone, "****", 3, 7);
    }

    /**
     * 格式化卡号（卡号脱敏）
     *
     * @param card
     * @return
     */
    public static String getLastCardId(String card) {
        if (StringUtils.isEmpty(card) || card.length() <= 8) {
            return card;
        }
        return card.substring(card.length() - 4, card.length());
    }


    /**
     * 格式化名字（名字脱敏）
     *
     * @param name
     * @return
     */
    public static String formatName(String name) {
        if (StringUtils.isEmpty(name)) {
            return "";
        }
        if (name.length() == 2) {
            return replaceString(name, "*", 1, 2);
        }
        if (name.length() == 3) {
            return replaceString(name, "*", 1, 2);
        }
        if (name.length() == 11) {
            return formatPhone(name);
        }
        return name.length() >= 4 ? replaceString(name, "*", name.length() - 1, name.length()) : name;
    }

    public static String replaceString(String content, String replaceStr, int begin, int end) {
        if (StringUtils.isEmpty(content)) {
            return "";
        }
        if (StringUtils.isEmpty(replaceStr)) {
            return content;
        }
        if (begin < 0) {
            return content;
        }
        if (end > content.length()) {
            return content;
        }
        StringBuilder sb = new StringBuilder(content);
        sb.replace(begin, end, replaceStr);
        return sb.toString();
    }

    /**
     * 将以分转为百分数
     *
     * @param num
     * @return
     */
    public static String F2Percentformat(Object num) {
        double d = Double.valueOf(num.toString());
        d = d / 10000;
        DecimalFormat df = new DecimalFormat("0.00%");
        String result = df.format(d);
        return result;
    }

    /**
     * 格式化金额(加上最后两位00) 15->15.00
     *
     * @param amt
     * @return
     */
    public static String formatAmt(Object amt) {
        return new DecimalFormat("0.00").format(new BigDecimal(amt.toString()));
    }

    /**
     * 将以分为单位的金额转为元
     *
     * @param s
     * @return
     */
    public static String formatF2Y(Object s) {
        if (s != null && !StringUtils.isEmpty(s.toString())) {
            return new BigDecimal(s.toString()).setScale(4, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        }
        return "0.00";
    }

    /**
     * 将以元为单位的金额转为分
     *
     * @param s
     * @return
     */
    public static String formatY2F(Object s) {
        if (s != null && !StringUtils.isEmpty(s.toString())) {
            return new BigDecimal(s.toString()).setScale(4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).toString();
        }
        return "0";
    }

    public static String delayTime(String startTime, int minutes) {
        int nStartHour = Integer.parseInt(startTime.substring(0, 2));
        int nStartMin = Integer.parseInt(startTime.substring(2, 4));
        int nStart = nStartHour * 60 + nStartMin;
        nStart = nStart + minutes;
        return String.format("%02d", nStart / 60) + String.format("%02d", nStart % 60);
    }

}
